package com.rpframework.website.device.act.api;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.rpframework.core.BaseAct;
import com.rpframework.core.utils.MessageFormatter;
import com.rpframework.core.utils.TagUtils;
import com.rpframework.module.common.pay.alipay.util.AlipayNotify;
import com.rpframework.module.common.pay.wxpay.api.WXpayApi;
import com.rpframework.module.common.pay.wxpay.config.WXpayConfig;
import com.rpframework.module.common.pay.wxpay.util.WXpayCore;
import com.rpframework.utils.NumberUtils;
import com.rpframework.utils.Pager;
import com.rpframework.website.device.domain.Balance;
import com.rpframework.website.device.domain.Coupon;
import com.rpframework.website.device.domain.Estate;
import com.rpframework.website.device.domain.Goods;
import com.rpframework.website.device.domain.GoodsStock;
import com.rpframework.website.device.domain.GoodsStockRecord;
import com.rpframework.website.device.domain.Order;
import com.rpframework.website.device.domain.User;
import com.rpframework.website.device.exception.APICodeException;
import com.rpframework.website.device.service.BalanceService;
import com.rpframework.website.device.service.CouponService;
import com.rpframework.website.device.service.EstateService;
import com.rpframework.website.device.service.GoodsService;
import com.rpframework.website.device.service.GoodsStockRecordService;
import com.rpframework.website.device.service.GoodsStockService;
import com.rpframework.website.device.service.OrderService;
import com.rpframework.website.device.service.ShoppingCartService;
import com.rpframework.website.device.service.UserService;
import com.rpframework.website.device.util.PayUtils;

@Controller
@RequestMapping("/api/order")
public class OrderApiAct extends BaseAct {
	@Resource OrderService service;
	@Resource GoodsService goodsService;
	@Resource EstateService estateService;
	@Resource CouponService couponService;
	@Resource ShoppingCartService cartService;
	@Resource UserService userService;
	@Resource GoodsStockService stockService;
	@Resource GoodsStockRecordService recordService;
	@Resource BalanceService balanceService;
	int point = 0;
	double price = 0d;
	public static String ali_order_notify = "/api/order/test_order_notify";
	public static String alinotify = "/api/order/test_alipay_succ";
	public static String wxnotify = "/api/order/wx_pay_notify";
	public static String wx_order_notify = "/api/order/wx_order_notify";
	/**
	 * 从购物车 或 商品详情立即购买后展示的预订单信息
	 * @param callback
	 * @param ids
	 * @param amount
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/confirm",produces = "application/json; charset=utf-8")
	public @ResponseBody String Confirm(
			@RequestParam(value = "callback",required = false ) String callback,
			@RequestParam(value = "ids",required = false ) List<Integer> ids,
			@RequestParam(value = "amount",required = false ) List<Integer> amount,
			HttpSession session
			){
		JsonObject json = new JsonObject();
		User user=getSessionUser(session);
		if(user==null){
			throw new APICodeException(-4, "你还没登陆!");
		}
		Estate e = estateService.select(user.getEstateId());
		if(e==null){
			json.addProperty("succ", false);
			json.addProperty("msg", "商品无效");
			return (callback + "(" + json + ")");
		}
		
		json.addProperty("cnee", user.getRealName());
		json.addProperty("tel", user.getTel());
		json.addProperty("address", "我是收获地址，我要重新完善!");
		String time = TagUtils.formatDate(System.currentTimeMillis()/1000);
		json.addProperty("delivery", time.substring(time.length()-8,time.length()-3));//配送时间
		Double couponSet = e.getCouponSet();
		json.addProperty("couponSet",couponSet);
		point = 0;
		price = 0d;
		JsonArray array = getGoodsArray(ids,amount,-1);
		json.add("goods", array);
		json.addProperty("priceAmount", price);//商品总额
		json.addProperty("pointAmount",point);//可获得总积分
		Double attachPrice = e.getAttachPrice();
		Double attachSet = e.getAttachSet();
		json.addProperty("coupon",0);//优惠券
		json.addProperty("attach",price>=attachSet ? 0 : attachPrice);//配送费
		
		json.addProperty("attachSet",attachSet);
		json.addProperty("attachPrice",attachPrice);
		json.add("remark", service.getJsonInfo());
		return (callback + "(" + json + ")");
	}
		/**
		 * 获取订单里的一组商品信息
		 * @param ids
		 * @param amount
		 * @param relativeId 
		 * @return
		 */
		private JsonArray getGoodsArray(List<Integer> ids, List<Integer> amount, Integer relativeId) {//relativeId表示用户是哪个小区的
			JsonArray array = new JsonArray();
			for(int i =0;i<ids.size();i++){
				Goods goods = goodsService.select(ids.get(i));
				if(goods==null){
					return null;
				}
				JsonObject obj = new JsonObject();
				/*商品信息*/
				obj.addProperty("id", goods.getId());
				obj.addProperty("name", goods.getName());//商品名字
				obj.addProperty("amount", amount.get(i));//商品数量
				
				/*
				 * 每个商品的购买数量  同物业库存比较。如果大于物业库存  就查平台库存。并且减去差量
				 * 如果买的数量是小于物业的 ，直接扣除物业公司的数量。生成订单。如果数量大于物业。生成总数的订单，后台再默认为这个物业配送一条入库记录单，且状态为未确认，由物业公司自行确认。
				 */
				if(relativeId > 0){
					GoodsStock gs = stockService.searchStock(goods.getId(), relativeId);//查小区该商品库存
					if(gs !=null){
						if(amount.get(i) <= gs.getAmount()){
							gs.setAmount(gs.getAmount() - amount.get(i));
							//更改该商品在物业的库存
							gs.setModifyTime(System.currentTimeMillis()/1000);
							stockService.update(gs);
						}else{//用户购买大于物业库存，由于在页面上做了限制，故数量不可能超过平台-物业的总数
							//根据减量补配商品 平台会自动扣
							GoodsStockRecord t = new GoodsStockRecord();
							t.setAmount(amount.get(i) - gs.getAmount());
							t.setGoodsId(goods.getId());
							t.setRelativeId(relativeId);
							t.setStatus(2);//用户购买的 确认后不加库存
							recordService.doSaveOrUpdate(t);//生成补货记录
							gs.setAmount(0d);
							gs.setModifyTime(System.currentTimeMillis()/1000);
							stockService.update(gs);
						}
					}
				}
				
				obj.addProperty("price", amount.get(i)*(goods.getDisPrice() ==0 ? goods.getOldPrice() : goods.getDisPrice()));//每件商品总价格
				obj.add("urlList",new JsonParser().parse(goods.getUrlList()).getAsJsonArray());//每件商品总价格
				point = point + goods.getPoint()*amount.get(i);//所有商品可获得总积分
				price = price + amount.get(i)*(goods.getDisPrice() ==0 ? goods.getOldPrice() : goods.getDisPrice());//订单总额 每件商品的价格 * 数量相加
				array.add(obj);
			}
			return array;
	}

	//提交订单(商品的id,商品的数量)
	//删除购物车的(商品的id)
	//返回价格和支付宝信息
	/**
	 * 生成订单
	 * @param callback
	 * @param ids 商品id
	 * @param amount 商品数量
	 * @param couponId 优惠券id 
	 * @param price 商品金额  不计算以页面的数据为准
	 * @param point 总积分 不计算以页面的数据为准
	 * @param attach 配送费
	 * @param sendTime 配送时间
	 * @param remark 备注
	 * @param session 登录用户
	 * @return
	 */
	@RequestMapping(value="/create",produces = "application/json; charset=utf-8")
	public @ResponseBody String Create(
			@RequestParam(value = "callback",required = false ) String callback,
			//@RequestParam(value = "ids",required = false ) Integer[] ids,//商品id
			//@RequestParam(value = "amount",required = false ) Integer[] amount,//商品数量
			@RequestParam(value = "ids",required = false ) List<Integer> ids,//商品id
			@RequestParam(value = "amount",required = false ) List<Integer> amount,//商品数量
			@RequestParam(value = "couponId",required = false ) Integer couponId,//优惠券id 
			@RequestParam(value = "price",required = false ) Double price,//商品金额  不计算以页面的数据为准
			@RequestParam(value = "point",required = false ) Integer point,//总积分 不计算以页面的数据为准
			@RequestParam(value = "attach",required = false ) Double attach,//配送费
			@RequestParam(value = "sendTime",required = false ) String sendTime,//配送时间
			@RequestParam(value = "remark",required = false ) String remark,//备注
			
			HttpSession session
			){
		JsonObject json = new JsonObject();
		User user=getSessionUser(session);
		if(user==null){
			throw new APICodeException(-4, "你还没登陆!");
		}
		//当前登录user的地址信息
		Order t = new Order();
		t.setId(service.createOrderId());//生成订单id
			JsonObject juser = new JsonObject();
			juser.addProperty("id", user.getId());
			juser.addProperty("realName", user.getRealName());
			juser.addProperty("address", user.getRealName()+"的默认地址");
		t.setUser(juser.toString());//插入用户住址信息
		t.setUserId(user.getId());
		t.setEstateId(user.getEstateId());
		t.setAttach(attach);
		t.setGoods(getGoodsArray(ids,amount,user.getEstateId()).toString());//插入多个商品信息
		t.setPrice(price);
		t.setPoint(point);
		t.setSendTime(sendTime);//配送时间
		t.setState(1);
		t.setStatus(1);//订单状态 1待支付 2待发货 3 待收货 4 已完成
		t.setCreateTime(System.currentTimeMillis()/1000);
		t.setRemark(remark);
		Coupon c = null;
		if(NumberUtils.isValid(couponId)){
			JsonObject jcou = new JsonObject();
			c =  couponService.select(couponId);
			jcou.addProperty("id", c.getId());
			jcou.addProperty("price", c.getPrice());
			t.setCoupon(jcou.toString());//插入积分信息				
		}
		boolean f = service.insert(t);
		if(f){
			json.addProperty("orderId", t.getId());
			json.addProperty("price", t.getPrice());
			json.addProperty("balance", user.getBalance());
			if(c!=null){
				c.setState(2);//将优惠券占用
				couponService.update(c);
			}
			cartService.doCleanCart(ids);//将购物车买的商品移出购物车
		}else{
			json.addProperty("orderId", "");
			json.addProperty("msg", "创建订单失败！");
		}
		return (callback + "(" + json + ")");
	}
	/**
	 * 页面展示的平台有货或物业有货区重新查询，用户购买的商品数量超过物业的总数时 会显示从平台发货
	 * 每件商品都去物业查询一下，不够就下单，下多少是由用户购买的数量为准
	 * @param orderId
	 * @param relativeId
	 */
	public void check(String orderId,Integer relativeId){
		Order t = service.select(orderId);
		Integer id;
		Double amount;
		JsonArray arr = new JsonParser().parse(t.getGoods()).getAsJsonArray();
		for(int i = 0 ;i< arr.size(); i++){
			JsonObject obj = (JsonObject) arr.get(i);
			id = Integer.valueOf(obj.get("id").toString());
			amount = Double.valueOf(obj.get("amount").toString());
			GoodsStock g = stockService.searchStock(Integer.valueOf(id), relativeId);
			if(g!=null && g.getAmount() < amount){//如果库存数量 小于用户要购买的数量;要主动生成一个配送单，数额为警示数量。并标识为用户需求，注意发货。
				GoodsStockRecord record = new GoodsStockRecord();
				record.setGoodsId(id);//还要标识 这是由用户发起的
				record.setAmount(amount);//这里表示补货方式-- 补用户购买数量
				record.setRelativeId(relativeId);//补给此用户的小区
				record.setStatus(2);//用户购买需求
				recordService.doSaveOrUpdate(record);
			}
		}
	}
	@RequestMapping(value="/list" ,produces = "application/json; charset=utf-8")
	public @ResponseBody String List(@RequestParam(value="pager", required=false)Pager<Order> pager,//分页
			@RequestParam(value = "callback",required = false ) String callback,
			@RequestParam(value = "status",required = false ) Integer status,//订单状态 参数为空查询全部
			@RequestParam(value = "limit",required = false ) Integer limit,
			HttpSession session){//当前登录的用户的订单
		if(pager==null){
			pager=new Pager<Order>();
		}
		User user = getSessionUser(session);
		if(user == null){
			throw new APICodeException(-4, "你还没登陆!");
		}
		if(NumberUtils.isValid(limit))pager.setPageSize(limit);
		/*1.当前登录的用户的订单*/
		pager.getSearchMap().put("userId", user.getId().toString());
		/*2.订单的状态 如果参数为空查询全部*/
		if(NumberUtils.isValid(status))pager.getSearchMap().put("status", status.toString());
		pager=service.getPager(pager);
		
		JsonObject json=new JsonObject();
		json.addProperty("totalPages", pager.getTotalPages());
		json.addProperty("currentPage", pager.getCurrentPage());
		json.addProperty("totalCount", pager.getTotalCount());
		json.addProperty("balance",user.getBalance());
		List<Order> list=pager.getItemList();
		JsonArray array=new JsonArray();
		for(Order li : list){
			JsonObject obj = new JsonObject();
			obj.addProperty("orderId", li.getId());
			obj.addProperty("time", TagUtils.formatDate(li.getCreateTime()));
			obj.addProperty("status", li.getStatus());
			obj.addProperty("price", li.getPrice());
			obj.addProperty("isRemind", li.getIsRemind());
			obj.addProperty("isBack", li.getIsBack());//是否申请退款
			/*将json数据转成jsonArray*/
			JsonArray goods = new JsonParser().parse(li.getGoods()).getAsJsonArray();
			obj.add("goods", goods);//商品数组
			array.add(obj);
		}
		json.add("arrays", array);
		return (callback + "(" + json + ")");
	}
	@RequestMapping(value="/detail" ,produces = "application/json; charset=utf-8")
	public @ResponseBody String Detail(
			@RequestParam(value = "orderId") String orderId,//订单id
			@RequestParam(value = "callback",required = false ) String callback,
			HttpSession session){//当前登录的用户的订单
		User user = getSessionUser(session);
		if(user == null){
			throw new APICodeException(-4, "你还没登陆!");
		}
		JsonObject json=new JsonObject();
		if(StringUtils.isNotBlank(orderId)){
			Order t = service.select(orderId);
			if(t!=null){
				json.addProperty("code", 200);
				json.addProperty("status", t.getStatus());
				json.addProperty("userName", user.getRealName());
				json.addProperty("tel", user.getTel());
				json.addProperty("address", "我是收获地址，我要重新完善!");
				JsonArray goods = new JsonParser().parse(t.getGoods()).getAsJsonArray();//取出json数组
				json.add("goods", goods);//商品数组
				json.addProperty("orderId", t.getId());
				json.addProperty("sendTime", t.getSendTime());
				json.addProperty("payChannel", t.getPayChannel());//1 余额 2支付宝 3微信
				json.addProperty("createTime", TagUtils.formatDate(t.getCreateTime()));
				json.addProperty("remark", t.getRemark());
				json.addProperty("realPrice", t.getPrice());
				json.addProperty("point", t.getPoint());
				json.addProperty("attach", t.getAttach());
				json.addProperty("isRemind", t.getIsRemind());//是否催单 
				json.addProperty("isBack", t.getIsBack());//是否申请退款
				Integer couponPrice = 0;
				if(StringUtils.isNotBlank(t.getCoupon())){
					JsonObject obj = new JsonParser().parse(t.getCoupon()).getAsJsonObject();
					couponPrice = Integer.valueOf(obj.get("price").toString());
					json.addProperty("coupon", couponPrice);//取出优惠券里的券额
				}else{
					json.addProperty("coupon", 0);//取出优惠券里的券额
				}
				//实际金额 - 配送费 - 优惠券额就是商品金额  另一种是商品在下订单的时候，把商品金额存到数据库
				json.addProperty("goodsPrice", t.getPrice() - t.getAttach() - couponPrice);
				Estate estate = estateService.select(t.getEstateId());
				if(estate!=null)
				json.addProperty("estateTel", estate.getLinkTel());//物业联系电话 没有写空
				else json.addProperty("estateTel", "");
			}
		}
		return (callback + "(" + json + ")");
	}
	/**
	 * 订单处理
	 * 取消订单
	 * 取消订单要把商品还回物业
	 * 确认订单
	 * @param callback
	 * @param orderId
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/handle" ,produces = "application/json; charset=utf-8")
	public @ResponseBody String Cancel(
			@RequestParam(value = "callback",required = false ) String callback,
			@RequestParam(value = "orderId") String orderId,//订单id
			@RequestParam(value = "causeId") Integer causeId,//退款原因 退款时填写
			@RequestParam(value = "type") String type,//
			HttpSession session){//当前登录的用户的订单
		User user = getSessionUser(session);
		if(user == null){
			throw new APICodeException(-4, "你还没登陆!");
		}
		JsonObject json=new JsonObject();
		boolean flag = false;
		if(StringUtils.isNotBlank(type) && StringUtils.isNotBlank(orderId)){
			Order t = service.select(orderId);
			if(t!=null){
				//删除订单
				if("cancel".equals(type)){
					flag = service.delete(orderId);
					json = service.getBooleanJson(flag);
					return (callback + "(" + json + ")");
				}
				//确认订单 把status 变为4
				if("sub".equals(type)){
					t.setStatus(4);
				}
				//催单
				if("reminder".equals(type)){
					t.setIsRemind(2);//表示已经催单
				}
				//删除订单
				if("back".equals(type)){
					t.setIsBack(2);//将改为已申请退款状态 
					if(NumberUtils.isValid(causeId))
					t.setCauseId(causeId);
				}
				t.setModifyTime(System.currentTimeMillis()/1000);
				flag = service.update(t);
			}
		}
		json = service.getBooleanJson(flag);
		return (callback + "(" + json + ")");
	}
	/**
	 * 订单支付
	 * @param callback
	 * @param orderId
	 * @param payChannel 1支付宝 2微信 3余额
	 * @param session
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/pay",produces = "application/json; charset=utf-8")
	public @ResponseBody String Pay(
			@RequestParam(value = "callback",required = false ) String callback,
			@RequestParam(value = "orderId",required = false ) String orderId,//订单号
			@RequestParam(value = "payChannel",required = false ) Integer payChannel,
			HttpSession session
			) throws UnsupportedEncodingException{
		JsonObject json = new JsonObject();
		User user=getSessionUser(session);
		if(user==null){
			throw new APICodeException(-4, "你还没登陆!");
		}
		//当前登录user的信息
		Order t = service.select(orderId);
		if(t==null){
			json.addProperty("code", 500);
			json.addProperty("msg", "支付失败！");
		}
		//t.getPrice();
		if(payChannel == 3){
			if(t.getStatus() == 2){
				json.addProperty("code", 500);
				json.addProperty("msg", "订单已支付,不能重复支付！");
				return (callback + "(" + json + ")");
			}
			if(user.getBalance() >= t.getPrice()){
				user.setBalance(user.getBalance() - t.getPrice());
				t.setStatus(2);//订单状态 1待支付 2待发货 3 待收货 4 已完成
				t.setModifyTime(System.currentTimeMillis()/1000);
				boolean f1 = userService.update(user);
				boolean f2 = service.update(t);
				//添加余额明细
				boolean f3 = balanceService.addRecord(-t.getPrice(),t.getName(),1,t.getUserId());
				if(!f1 && f2 && f3){
					json.addProperty("code", 500);
					json.addProperty("msg", "支付失败！");
				}else{
					json.addProperty("code", 200);
					user.setPoint(user.getPoint()+t.getPoint());
					userService.update(user);
					json.addProperty("msg", "支付成功！");
				}
				return (callback + "(" + json + ")");
			}
		}
		if(payChannel == 1){
			if(t.getState() == 1){
				if(t.getStatus() == 2){
					json.addProperty("code", 500);
					json.addProperty("msg", "订单已支付,不能重复支付！");
					return (callback + "(" + json + ")");
				}
				return PayUtils.AliPay(t.getId(), t.getPrice(), user.getNickName(), user.getNickName(), ali_order_notify, callback);
			}else{
				json.addProperty("code", 500);
				json.addProperty("msg", "订单无效,原因是订单已支付");
			}
			return (callback + "(" + json + ")");
		}
		if(payChannel == 2){
			if(t.getStatus() == 2){
				json.addProperty("code", 500);
				json.addProperty("msg", "订单已支付,不能重复支付！");
				return (callback + "(" + json + ")");
			}
			return PayUtils.WxPay(t.getId(),t.getPrice(),user.getNickName(), wx_order_notify,callback);
		}
		return (callback + "(" + json + ")");
	}
	
	
	
	/**
	 * 支付宝充值
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/alipay",produces = "application/json; charset=utf-8")
	public @ResponseBody String AliPay(
			@RequestParam(value = "callback",required = false ) String callback,
			@RequestParam(value = "money",required = false ) Double money,
			@RequestParam(value = "payChannel",required = false ) Integer payChannel,
			HttpSession session
			) throws UnsupportedEncodingException{
		JsonObject json = new JsonObject();
		User user=getSessionUser(session);
		if(user==null){
			throw new APICodeException(-4, "你还没登陆!");
		}
		Balance t = new Balance();
		t.setId(service.createOrderId());//生成订单id
		t.setCreateTime(System.currentTimeMillis()/1000);
		t.setMoney(money);
		t.setName("充值");
		t.setType(1);
		t.setUserId(user.getId());
		t.setState(2);
		boolean f = balanceService.insert(t);
		if(f){
			if(payChannel == 1){
				return PayUtils.AliPay(t.getId(), t.getMoney(), user.getNickName(), user.getNickName(), alinotify, callback);
			}else if(payChannel == 2){
				return PayUtils.WxPay(t.getId(), t.getMoney(),user.getNickName(),wxnotify,callback);
			}
		}
		return (callback + "(" + json + ")");
	}
	/*支付宝充值回调*/
	@SuppressWarnings({ "rawtypes", "unused" })
	@RequestMapping("/test_alipay_succ")
	public @ResponseBody String TestAliPaySucc(HttpServletRequest request) throws UnsupportedEncodingException{
		
		Logger logger = LoggerFactory.getLogger(getClass());
		logger.info("pay: 进入回调...." );
		String ret = "";
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		
		//订单号 100524+10位随机数
		String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
		//支付宝交易号
		//交易状态
		String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
		logger.info("pay: 订单号："+out_trade_no+" \t 状态："+trade_status);
		
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		// 支付宝交易号
		String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
		// 买家支付宝
		String buyerEmail = new String(request.getParameter("buyer_email").getBytes("ISO-8859-1"), "UTF-8");
		// 卖家支付宝
		String seller_email = new String(request.getParameter("seller_email").getBytes("ISO-8859-1"), "UTF-8");
		// 支付时间
		String notify_time = new String(request.getParameter("notify_time").getBytes("ISO-8859-1"), "UTF-8");
		// 交易状态
		String tradeStatus = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
		// 买家支付宝账户编号
		String buyer_id = new String(request.getParameter("buyer_id").getBytes("ISO-8859-1"), "UTF-8");
		
		if(AlipayNotify.verify(params)){//验证成功
			logger.info("pay: 验证succ=============");
			double total_fee = NumberUtils.parseDouble(request.getParameter("total_fee"));
			//////////////////////////////////////////////////////////////////////////////////////////
			if (trade_status.equals("TRADE_FINISHED")|| trade_status.equals("TRADE_SUCCESS")) {
				Balance t = balanceService.select(out_trade_no);
				t.setState(1);
				boolean f1 = balanceService.update(t);
				boolean f2= false;
				if(f1){
					User user = userService.select(t.getUserId());
					if(user !=null){
						user.setBalance(user.getBalance()+t.getMoney());
					}
					f2 = userService.update(user);
				}
				logger.info("pay: 订单状态更新：" + f2);
				/**
				 * 这里有支付记录的逻辑
				 * 记录表插入一条数据
				 */
			}
			//请在这里加上商户的业务逻辑程序代码
			ret = "success";	//请不要修改或删除
			//////////////////////////////////////////////////////////////////////////////////////////
		}else{//验证失败
			logger.info("pay: error==========================");
			ret = "fail";
		}
		return ret;
	} 	
	/*支付宝订单回调*/
	@SuppressWarnings({ "rawtypes", "unused" })
	@RequestMapping("/test_order_notify")
	public @ResponseBody String TestPaySucc(HttpServletRequest request) throws UnsupportedEncodingException{
		
		Logger logger = LoggerFactory.getLogger(getClass());
		logger.info("pay: 进入回调...." );
		String ret = "";
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		
		//订单号 100524+10位随机数
		String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
		//支付宝交易号
		//交易状态
		String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
		logger.info("pay: 订单号："+out_trade_no+" \t 状态："+trade_status);
		
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		// 支付宝交易号
		String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
		// 买家支付宝
		String buyerEmail = new String(request.getParameter("buyer_email").getBytes("ISO-8859-1"), "UTF-8");
		// 卖家支付宝
		String seller_email = new String(request.getParameter("seller_email").getBytes("ISO-8859-1"), "UTF-8");
		// 支付时间
		String notify_time = new String(request.getParameter("notify_time").getBytes("ISO-8859-1"), "UTF-8");
		// 交易状态
		String tradeStatus = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
		// 买家支付宝账户编号
		String buyer_id = new String(request.getParameter("buyer_id").getBytes("ISO-8859-1"), "UTF-8");
		
		if(AlipayNotify.verify(params)){//验证成功
			logger.info("pay: 验证succ=============");
			double total_fee = NumberUtils.parseDouble(request.getParameter("total_fee"));
			//////////////////////////////////////////////////////////////////////////////////////////
			if (trade_status.equals("TRADE_FINISHED")|| trade_status.equals("TRADE_SUCCESS")) {
				Order t = service.select(trade_no);
				t.setStatus(2);
				t.setModifyTime(System.currentTimeMillis()/1000);
				boolean f1 = service.update(t);
				boolean f2 = false;
				if(f1){
					User user = userService.select(t.getUserId());
					if(user !=null){
						user.setPoint(user.getPoint()+t.getPoint());
					}
					f2 = userService.update(user);
				}
				logger.info("pay: 订单状态更新：" + f2);
				/**
				 * 这里有支付记录的逻辑
				 * 记录表插入一条数据
				 */
			}
			//请在这里加上商户的业务逻辑程序代码
			ret = "success";	//请不要修改或删除
			//////////////////////////////////////////////////////////////////////////////////////////
		}else{//验证失败
			logger.info("pay: error==========================");
			ret = "fail";
		}
		return ret;
	} 	
	
	/*微信订单回调*/
	@RequestMapping("wx_order_notify")
	public @ResponseBody String wxNotify(@RequestBody String body,
			HttpServletRequest request) throws UnsupportedEncodingException {
		String ret = "<xml><return_code><![CDATA[{}]]></return_code> <return_msg><![CDATA[{}]]></return_msg></xml>";
		System.out.println(body);
		//PAY.info("wxNotify--" + body);
		Map<String, String> retMap = WXpayCore.getRetMap(body);
		boolean retSuccess = WXpayCore.isRetSuccess(retMap);
		
		if(retSuccess) {
			double total_fee = NumberUtils.parseDouble(retMap.get("total_fee"));
			total_fee /= 100; //分转化为元
			
			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			String out_trade_no = retMap.get("out_trade_no");
			
			Order t = service.select(out_trade_no);
			if(t==null){
				System.out.println("===================订单不存在=========================");			
			}else{
				t.setModifyTime(System.currentTimeMillis()/1000);
				t.setStatus(2);
				boolean f = service.update(t);
				if(f){
					System.out.println("===================更改状态成功=========================");			
				}else{
					System.out.println("===================更改状态失败=========================");			
				}
			}
			try {
				ret = MessageFormatter.format(ret, "SUCCESS", "OK");
			} catch (Exception e) {
				e.printStackTrace();
				ret = MessageFormatter.format(ret, "FAIL", e.getLocalizedMessage());
			}
		} 
		return ret;
	}
	/*微信充值回调*/
	@RequestMapping("wx_pay_notify")
	public @ResponseBody String wx_pay_notify(@RequestBody String body,
			HttpServletRequest request) throws UnsupportedEncodingException {
		String ret = "<xml><return_code><![CDATA[{}]]></return_code> <return_msg><![CDATA[{}]]></return_msg></xml>";
		System.out.println(body);
		//PAY.info("wxNotify--" + body);
		Map<String, String> retMap = WXpayCore.getRetMap(body);
		boolean retSuccess = WXpayCore.isRetSuccess(retMap);
		
		if(retSuccess) {
			double total_fee = NumberUtils.parseDouble(retMap.get("total_fee"));
			total_fee /= 100; //分转化为元
			
			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			String out_trade_no = retMap.get("out_trade_no");
			Balance t = balanceService.select(out_trade_no);
			
			if(t==null){
				System.out.println("===================充值订单不存在=========================");			
			}else{
				t.setState(1);
				boolean f = balanceService.update(t);
				if(f){
					User user = userService.select(t.getUserId());
					if(user !=null){
						user.setBalance(user.getBalance()+t.getMoney());
					}
					boolean f2 = userService.update(user);
					if(f2)
					System.out.println("===================充值成功=========================");			
				}else{
					System.out.println("===================充值失败=========================");			
				}
			}
			try {
				ret = MessageFormatter.format(ret, "SUCCESS", "OK");
			} catch (Exception e) {
				e.printStackTrace();
				ret = MessageFormatter.format(ret, "FAIL", e.getLocalizedMessage());
			}
		} 
		return ret;
	}
	
}
